package hu.kisszoltan.boxescape.gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.util.Random;

public class Enemy extends GameObject {

	private Polygon me;

	private int width = 0;

	private int height = 0;

	private int x = 0;

	private int y = 0;

	private int[] defaults = new int[4];

	private float accuracy[] = new float[] { 4.0f, 4.0f };

	public Enemy(GamePane gamePane, int width, int height, int x, int y) {
		super(gamePane);
		this.width = defaults[0] = width;
		this.height = defaults[1] = height;
		this.x = defaults[2] = x;
		this.y = defaults[3] = y;

		setColor(Color.BLUE);
		me = getPolygon();
		randomize();
	}

	private void randomize() {
		Random r = new Random();

		accuracy[0] = (r.nextBoolean() ? 1.0f : -1.0f) * (accuracy[0] + 0.5f * r.nextFloat());
		accuracy[1] = (r.nextBoolean() ? 1.0f : -1.0f) * (accuracy[1] + 0.5f * r.nextFloat());
	}

	@Override
	public synchronized Polygon getPolygon() {
		if (me == null) {
			me = new Polygon();
			me.addPoint(x, y);
			me.addPoint(x + width, y);
			me.addPoint(x + width, y + height);
			me.addPoint(x, y + height);
		}
		return me;
	}

	@Override
	public void paint(Graphics g) {
		g.setColor(getColor());
		g.fillPolygon(me);
	}

	@Override
	public synchronized void moveTo(int x, int y) {
		this.x = x;
		this.y = y;
		me = null;
		me = getPolygon();
	}

	@Override
	public void moveBy(float scaleX, float scaleY) {
		this.x *= scaleX;
		this.y *= scaleY;
		me = null;
		me = getPolygon();
	}

	public void update() {
		int newX = x + Math.round(accuracy[0]);
		int newY = y + Math.round(accuracy[1]);

		if (newX < 0 || newX + width > parent.getWidth()) {
			accuracy[0] = -accuracy[0];
			newX = x + Math.round(accuracy[0]);
		}

		if (newY < 0 || newY + height > parent.getHeight()) {
			accuracy[1] = -accuracy[1];
			newY = y + Math.round(accuracy[1]);
		}

		moveTo(newX, newY);
	}

	@Override
	public void reset() {
		this.width = defaults[0];
		this.height = defaults[1];
		this.x = defaults[2];
		this.y = defaults[3];

		this.accuracy = new float[] { 4.0f, 4.0f };

		moveTo(x, y);
		randomize();
	}

	@Override
	public void speedUp(int level) {
		accuracy[0] += Math.signum(accuracy[0]) * ((float) level / 1000);
		accuracy[1] += Math.signum(accuracy[0]) * ((float) level / 1000);
	}
}
